package books4all

import org.springframework.dao.DataIntegrityViolationException
import grails.plugins.springsecurity.Secured

class LivreController {
	
	def springSecurityService

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index() {
        redirect(action: "list", params: params)
    }

	@Secured(['ROLE_ADMIN'])
    def list() {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [livreInstanceList: Livre.list(params), livreInstanceTotal: Livre.count()]
    }
	
	def listPerso() {
		def courant = springSecurityService.currentUser
		String username = courant.username
		params.max = Math.min(params.max ? params.int('max') : 10, 100)
		[livreInstanceList: User.findByUsername(username).biblio, livreInstanceTotal: User.findByUsername(username).biblio.size()]
	}

    def create() {
        [livreInstance: new Livre(params)]
    }

    def save() {
		def f = request.getFile('fic')
		if(!f.empty) {
			params.fichier =  f.getOriginalFilename() 
			f.transferTo(new File("web-app/"+params.fichier))
		}
		else {
		   flash.message = 'file cannot be empty'
		   render(view:'uploadForm')
		}
		
		def livreInstance = new Livre(params)
		def courant = springSecurityService.currentUser
		String username = courant.username
		User.findByUsername(username).addToBiblio(livreInstance)
        if (!livreInstance.save(flush: true)) {
            render(view: "create", model: [livreInstance: livreInstance])
            return
        }

		flash.message = message(code: 'default.created.message', args: [message(code: 'livre.label', default: 'Livre'), livreInstance.id])
        redirect(action: "listPerso")
    }

	@Secured(['ROLE_ADMIN'])
    def show() {
        def livreInstance = Livre.get(params.id)
        if (!livreInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'livre.label', default: 'Livre'), params.id])
            redirect(action: "list")
            return
        }

        [livreInstance: livreInstance]
    }
	
	def showLivreAmi() {
		def livreInstance = Livre.get(params.id)
		if (!livreInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'livre.label', default: 'Livre'), params.id])
			redirect(action: "list")
			return
		}

		[livreInstance: livreInstance]
	}
	
	def showPerso() {
		def livreInstance = Livre.get(params.id)
		if (!livreInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'livre.label', default: 'Livre'), params.id])
			redirect(action: "list")
			return
		}

		[livreInstance: livreInstance]
	}

    def edit() {
        def livreInstance = Livre.get(params.id)
        if (!livreInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'livre.label', default: 'Livre'), params.id])
            redirect(action: "listPerso")
            return
        }

        [livreInstance: livreInstance]
    }

    def update() {
        def livreInstance = Livre.get(params.id)
        if (!livreInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'livre.label', default: 'Livre'), params.id])
            redirect(action: "listPerso")
            return
        }

        if (params.version) {
            def version = params.version.toLong()
            if (livreInstance.version > version) {
                livreInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'livre.label', default: 'Livre')] as Object[],
                          "Another user has updated this Livre while you were editing")
                render(view: "edit", model: [livreInstance: livreInstance])
                return
            }
        }

        livreInstance.properties = params

        if (!livreInstance.save(flush: true)) {
            render(view: "edit", model: [livreInstance: livreInstance])
            return
        }

		flash.message = message(code: 'default.updated.message', args: [message(code: 'livre.label', default: 'Livre'), livreInstance.id])
        redirect(action: "show", id: livreInstance.id)
    }

    def delete() {
        def livreInstance = Livre.get(params.id)
        if (!livreInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'livre.label', default: 'Livre'), params.id])
            redirect(action: "list")
            return
        }

        try {
			User.list().each {
				def rep = false
				it.biblio.each {
					if(it==livreInstance)
						rep = true
				}
				if(rep)
					it.removeFromBiblio(livreInstance)
			}
            livreInstance.delete(flush: true)
			flash.message = message(code: 'default.deleted.message', args: [message(code: 'livre.label', default: 'Livre'), params.id])
            redirect(action: "listPerso")
        }
        catch (DataIntegrityViolationException e) {
			flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'livre.label', default: 'Livre'), params.id])
            redirect(action: "show", id: params.id)
        }
    }
}
